<?php

namespace app\index\controller;

use think\Db;
use EasyWeChat\Factory;

class Notify
{

    public function wxPayConfig()
    {

        $config = [
            // 必要配置
            'app_id' => config('wechat.AppId'),
            'mch_id' => config('wechat.MchId'),
            'key' => config('wechat.ApiKey'),   // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
//            'cert_path'          => '', // XXX: 绝对路径！！！！
//            'key_path'           => '',      // XXX: 绝对路径！！！！
//            'notify_url'         => request()->domain().'/index/pay/wxPayNotify',     // 你也可以在下单时单独设置来想覆盖它
        ];
        return Factory::payment($config);
    }

    //微信支付回调
    public function wxPayNotify()
    {

        $app = $this->wxPayConfig();

        $response = $app->handlePaidNotify(function ($message, $fail) {

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

//            file_put_contents('order.txt',json_encode($message).$message['out_trade_no']);
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
                $order = Db::name('order')->alias('a')
                    ->field('a.id,a.uid,a.pid,a.type,a.ppid,a.total_fee,a.commission1,b.pay_money,a.commission2,a.status,a.other_id,b.level,b.earnings,b.total_earnings,b.level_validity,b.sales,b.sales_validity')
                    ->leftJoin('user b', 'a.uid=b.id')
                    ->where(['a.out_trade_no' => "{$message['out_trade_no']}"])
                    ->find();

                if (!$order || $order['status'] > 0) { // 如果订单不存在 或者 订单已经支付过了

                    return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
                }


                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {

                    Db::startTrans();

                    //修改订单信息
                    $updData = [
                        'status' => 1,
                        'pay_time' => strtotime($message['time_end']),
                        'transaction_id' => $message['transaction_id'],
                        'pay_fee' => $message['total_fee'] / 100
                    ];

                    $upd = Db::name('order')->where('id', $order['id'])->update($updData);

                    if (!$upd) {
                        Db::rollback();

                        return $fail('修改订单失败');
                    }


                    //
                    $vip = Db::name('user_sales')->field('id,commission1,commission2')->order('price desc')->find();


                    if ($order['pid'] && $order['commission1']>0) {

                        //上级分佣
                        $upd = Db::name('user')->where('id', $order['pid'])
                            ->inc('earnings', $order['commission1'])
                            ->inc('total_earnings', $order['commission1'])
                            ->update();
//                            ->setInc('earnings', $order['commission1']);
                        if (!$upd) {
                            Db::rollback();

                            return $fail('上级分佣失败');
                        }

                        $max_money = empty($vip['commission1']) ? $order['commission1'] : round($order['total_fee'] * $vip['commission1'] / 100, 2);
                        $record = [
                            'uid' => $order['pid'],
                            'order_id' => $order['id'],
                            'money' => $order['commission1'],
                            'max_money' => $max_money,
                            'create_time' => $updData['pay_time'],
                            'user_type' => 1,
                            'pay_uid' => $order['uid'],
                            'pay_money' => $order['total_fee'],
                            'gx' => 1

                        ];


                        $add_record = Db::name('earnings')->insert($record);
                        if (!$add_record) {
                            Db::rollback();

                            return $fail('记录分佣失败');
                        }
                    }

                    if ($order['ppid'] && $order['commission2']>0) {
                        //上上级分佣
                        $upd = Db::name('user')->where('id', $order['ppid'])
                            ->inc('earnings', $order['commission2'])
                            ->inc('total_earnings', $order['commission2'])
                            ->update();
//                            ->setInc('earnings', $order['commission2']);
                        if (!$upd) {
                            Db::rollback();

                            return $fail('上上级分佣失败');
                        }
                        $max_money = empty($vip['commission2']) ? $order['commission2'] : round($order['total_fee'] * $vip['commission2'] / 100, 2);

                        $record = [
                            'uid' => $order['ppid'],
                            'order_id' => $order['id'],
                            'money' => $order['commission2'],
                            'max_money' => $max_money,
                            'create_time' => $updData['pay_time'],
                            'user_type' => 1,
                            'pay_uid' => $order['uid'],
                            'pay_money' => $order['total_fee'],
                            'gx' => 2

                        ];

                        $add_record = Db::name('earnings')->insert($record);
                        if (!$add_record) {
                            Db::rollback();

                            return $fail('记录分佣失败');
                        }
                    }

                    $updUser = ['pay_money' => $order['pay_money'] + $updData['pay_fee']];

                    if ($order['type'] == 1) {   #充值会员

                        //修改用户会员等级

                        $time = time();

                        //等级有效天数
                        $days = Db::name('user_level')->where('id', $order['other_id'])->value('day');

                        $days *= 86400;
//                        $year = 31536000; //年秒数
                        $updUser['level'] = $order['other_id'];

                        if ($order['level'] == 0) {

                            //首次充值
//                            $updUser['level'] = $order['other_id'];
                            $updUser['level_validity'] = $days + $time;

                        } else {

                            //重复充值
                            if ($order['level_validity'] < $time) {
                                //会员已过期 从当前时间开始算
                                $updUser['level_validity'] = $time + $days;
                            } else {
                                $updUser['level_validity'] = $order['level_validity'] + $days;
                            }

                        }


                    }elseif($order['type'] ==2){
                        //修改用户会员等级

                        $time = time();

                        //等级有效天数
                        $days = Db::name('user_sales')->where('id', $order['other_id'])->value('day');

                        $days *= 86400;
//                        $year = 31536000; //年秒数
                        if ($order['sales'] == 0) {

                            //首次充值
                            $updUser['sales'] = $order['other_id'];
                            $updUser['sales_validity'] = $days + $time;

                        } else {

                            $updUser['sales'] = $order['other_id'];

                            //重复充值
                            if($order['other_id']==$order['sales'] && $order['sales_validity']>=$time){
                                $updUser['sales_validity'] = $order['sales_validity'] + $days;

                            }else{
                                $updUser['sales_validity'] = $time + $days;

                            }


                        }
                    }


                    $upd = Db::name('user')->where('id', $order['uid'])->update($updUser);
                    if (!$upd) {
                        Db::rollback();

                        return $fail('修改会员失败');
                    }

                    Db::commit();


                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
                    file_put_contents('orderInfo.txt','订单有误');

//                    $order->status = 'paid_fail';
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }


            return true; // 返回处理完成
        });

        $response->send(); // return $response;
    }


    public function aliPayNotify()
    {

        include_once '../vendor/alipay/config.php';
        include_once '../vendor/alipay/wappay/service/AlipayTradeService.php';

        $config = config('alipay.');

        $arr = $_POST;
        //商户订单号

        $out_trade_no = $_POST['out_trade_no'];

        //支付宝交易号

        $trade_no = $_POST['trade_no'];

        //交易状态
        $trade_status = $_POST['trade_status'];

        $order = Db::name('order')->alias('a')
            ->field('a.id,a.uid,a.pid,a.type,a.ppid,a.total_fee,a.commission1,b.pay_money,a.commission2,a.status,a.other_id,b.level,b.earnings,b.total_earnings,b.level_validity')
            ->leftJoin('user b', 'a.uid=b.id')
            ->where(['a.out_trade_no' => "$out_trade_no"])
            ->find();

        if (empty($order)) {
            exit('fail');
        }

//        $alipaySevice = new \AlipayTradeService($config);
//
//        $alipaySevice->writeLog(var_export($_POST, true));
//        $result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */

        if ($order) {//验证成功


            if (!$order || $order['status'] > 0) {

                exit('success'); // 告诉支付宝，我已经处理完了
            }


            if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                Db::startTrans();

                //修改订单信息
                $updData = [
                    'status' => 1,
                    'pay_time' => strtotime($arr['gmt_payment']),
                    'transaction_id' => $trade_no,
                    'pay_fee' => $arr['total_amount']
                ];

                $upd = Db::name('order')->where('id', $order['id'])->update($updData);

                if (!$upd) {

                    Db::rollback();
                    exit('fail');
                }


                //股东等级分佣信息
                $vip = Db::name('user_level')->field('id,commission1,commission2')->order('price desc')->find();

                if ($order['pid'] && $order['commission1']) {
                    //上级分佣
                    $upd = Db::name('user')->where('id', $order['pid'])
                        ->inc('earnings', $order['commission1'])
                        ->inc('total_earnings', $order['commission1'])
                        ->update();
//                            ->setInc('earnings', $order['commission1']);
                    if (!$upd) {
                        Db::rollback();

                        exit('fail');
                    }

                    $max_money = empty($vip['commission1']) ? $order['commission1'] : round($order['total_fee'] * $vip['commission1'] / 100, 2);
                    $record = [
                        'uid' => $order['pid'],
                        'order_id' => $order['id'],
                        'money' => $order['commission1'],
                        'max_money' => $max_money,
                        'create_time' => $updData['pay_time'],
                        'user_type' => 1,
                        'pay_uid' => $order['uid'],
                        'pay_money' => $order['total_fee'],
                        'gx' => 1


                    ];

                    $add_record = Db::name('earnings')->insert($record);
                    if (!$add_record) {
                        Db::rollback();

                        exit('fail');
                    }
                }

                if ($order['ppid'] && $order['commission2']) {
                    //上上级分佣
                    $upd = Db::name('user')->where('id', $order['ppid'])
                        ->inc('earnings', $order['commission2'])
                        ->inc('total_earnings', $order['commission2'])
                        ->update();
//                            ->setInc('earnings', $order['commission2']);
                    if (!$upd) {
                        Db::rollback();

                        exit('fail');
                    }

                    $max_money = empty($vip['commission2']) ? $order['commission2'] : round($order['total_fee'] * $vip['commission2'] / 100, 2);

                    $record = [
                        'uid' => $order['ppid'],
                        'order_id' => $order['id'],
                        'money' => $order['commission2'],
                        'max_money' => $max_money,
                        'create_time' => $updData['pay_time'],
                        'user_type' => 1,
                        'pay_uid' => $order['uid'],
                        'pay_money' => $order['total_fee'],
                        'gx' => 2


                    ];

                    $add_record = Db::name('earnings')->insert($record);
                    if (!$add_record) {

                        Db::rollback();

                        exit('fail');
                    }
                }

                $updUser = ['pay_money' => $order['pay_money'] + $updData['pay_fee']];

                if ($order['type'] == 1) {   #充值会员

                    //修改用户会员等级

                    $time = time();
                    $year = 31536000; //年秒数
                    if ($order['level'] == 0) {

                        //首次充值
                        $updUser['level'] = $order['other_id'];
                        $updUser['level_validity'] = $time + $year;

                    } else {

                        //升级或重复充值
                        if ($order['other_id'] == $order['level']) {

                            //重复充值
                            if ($order['level_validity'] < $time) {
                                //会员已过期 从当前时间开始算
                                $updUser['level_validity'] = $time + $year;
                            } else {
                                $updUser['level_validity'] = $order['level_validity'] + $year;
                            }

                        } else {

                            $user_level = Db::name('user_level')->where('id', $order['level'])->value('price');

                            $new_level = Db::name('user_level')->where('id', $order['other_id'])->value('price');

                            //升级
                            if ($new_level > $user_level || $order['level_validity'] < $time) {
                                $updUser['level'] = $order['other_id'];
                                $updUser['level_validity'] = $time + $year;

                            }
                        }
                    }


                    //升级股东 24小时内的收益变更为股东最大收益
                    if (!empty($vip['id']) && $order['other_id'] == $vip['id']) {

                        $end = time();
                        $start = $end - 86400;

                        $total = Db::name('earnings')
                            ->field('sum(money) as money,sum(max_money) as max_money')
                            ->where('uid', $order['uid'])
                            ->where('is_max', 0)
                            ->where('create_time', 'between', "$start,$end")
                            ->find();

                        if (!empty($total['max_money'])) {
                            //变更收益
                            $updUser['total_earnings'] = $order['total_earnings'] - $total['money'] + $total['max_money'];
                            $updUser['earnings'] = $order['earnings'] - $total['money'] + $total['max_money'];

                            $upd = Db::name('earnings')
                                ->where('uid', $order['uid'])
                                ->where('is_max', 0)
                                ->where('create_time', 'between', "$start,$end")
                                ->exp('money', 'max_money')
                                ->update(
                                    [
                                        'is_max' => 1,
                                    ]
                                );

                            if (!$upd) {
                                Db::rollback();

                                exit('fail');
                            }

                        }

                    }

                }


                $upd = Db::name('user')->where('id', $order['uid'])->update($updUser);
                if (!$upd) {
                    Db::rollback();

                    exit('修改会员失败');
                }

                Db::commit();

                exit('success');
            } else {

                exit("fail");    //请不要修改或删除
            }

        } else {
            //验证失败

            exit("fail");    //请不要修改或删除

        }
    }
}